<template>
  <div id="account">
    <div class="header-box coll">
      <div class="form-flex">
        <div class="form-item">
          <div class="label">用户名</div>
          <el-input size="default" v-model.trim="query.username" style="margin-right: 10px" clearable placeholder="请输入">
          </el-input>
        </div>
        <div class="form-item">
          <div class="label">手机号码</div>
          <el-input size="default" v-model.trim="query.phone" style="margin-right: 10px" clearable placeholder="请输入">
          </el-input>
        </div>
        <div class="form-item">
          <el-button type="primary" size="default" @click="getAccounts">查询</el-button>
          <el-button type="primary" size="default" @click="addRow(ruleFormRef)">新增账号</el-button>
        </div>
      </div>
    </div>
    <div class="table-box coll">
      <el-table ref="workbenchTable" :height="state.tableHeight" :data="state.tableData" tooltip-effect="dark"
        empty-text="暂无数据" style="width: 100%" :header-cell-style="{
          textAlign: 'center',
          backgroundColor: '#f5f7fa'
        }" :cell-style="{ textAlign: 'center' }" :row-style="{ height: '80px' }">
        <el-table-column type="selection" width="60" fixed />
        <el-table-column label="序号" width="60">
          <template #default="scope">
            {{ scope.$index + 1 + (query.page - 1) * query.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="用户名" min-width="120px" prop="username" />
        <el-table-column label="邮箱" min-width="160px" prop="email" />
        <el-table-column label="电话" show-overflow-tooltip prop="phone" />
        <el-table-column label="角色" min-width="120px" prop="role_name">
          <template #default="scope">
            {{ scope.row.role_name ? scope.row.role_name : '普通用户' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="120px" prop="create_time" />
        <el-table-column label="操作" min-width="140px">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editRow(scope.row)">修改账号</el-button>
            <el-button size="small" type="danger" @click="removeRole(2, scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination v-model:currentPage="query.page" v-model:page-size="query.pageSize"
          :page-sizes="[10, 20, 50, 100, 300]" background layout="sizes,prev, pager, next" :total="state.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <span style="margin-right: 5px">当前共{{ state.total }}条</span>
        </el-pagination>
      </div>
    </div>
    <el-drawer ref="drawerRef" v-model="addDialog" :title="tabRole ? '修改角色' : '新增角色'" direction="rtl"
      custom-class="demo-drawer">
      <div class="demo-drawer__content">
        <el-form :model="form" ref="ruleFormRef" status-icon :rules="rules" class="demo-ruleForm">
          <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
            <el-input v-model="form.username" placeholder="请输入" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色" :label-width="formLabelWidth" prop="role_id">
            <el-select v-model="form.role_id" placeholder="请选择" style="width:100%;">
              <el-option v-for="(item, index) in state.roles" :key="index" :label="item.role_name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入" autocomplete="off" />
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input v-model="form.email" placeholder="请输入" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="treeClose(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="addRole(ruleFormRef)">{{ tabRole ? ' 修改' : '确认' }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, getCurrentInstance, ref } from 'vue'
import { ElDrawer, ElMessage, ElNotification, FormRules, ElTree, FormInstance } from 'element-plus'
import { getTableHeight } from '@/hooks/utils'
import { role } from '@/network/model/cartoonModel'

const state = reactive({
  tableHeight: 0,
  tableData: [],
  roles: [],
  total: 0,
  id: 0
})
const query = reactive({
  username: '',
  phone: '',
  page: 1,
  pageSize: 20
})
const form = reactive({
  username: '',
  email: '',
  phone: '',
  role_id: '',
})
const rules = reactive<FormRules>({
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }],
  role_id: [{ required: true, message: '请分配角色权限', trigger: 'blur' }]
})
const treeRef = ref<InstanceType<typeof ElTree>>()
const addDialog = ref(false)
const tabRole = ref(false)
const ruleFormRef = ref<FormInstance>()
const formLabelWidth = '80px'
// 获取公共接口
// @ts-ignore
const { proxy } = getCurrentInstance()
const api = proxy.$api
onMounted(async () => {
  state.tableHeight = getTableHeight(300)
  await getRoles()
  await getAccounts()
})
// 获取账号列表
async function getAccounts() {
  const res = await api.getAccounts(query)
  if (res.code == 200) {
    state.tableData = res?.data?.data
    state.total = res?.data?.total
    // 获取角色名称
    state.tableData.forEach(item => {
      const obj: any = state.roles.find(v => v.id == item.role_id)
      if (obj) {
        item.role_name = obj.role_name
      }
    })
  }
  console.log(res);
}
//  获取角色列表
async function getRoles() {
  const param = {
    isAll: true
  }
  const res = await api.getRoles(param)
  if (res.code == 200) {
    state.roles = res?.data?.data
  }
  console.log(state.roles);
}
// 打开添加角色
function addRow(formEl: FormInstance | undefined) {
  addDialog.value = true
  tabRole.value = false
  form.username = ''
  form.phone = ''
  form.email = ''
  form.role_id = ''
}
async function removeRole(type: number, id: string = '') {
  let ids: any = []
  // if (type == 1) {
  //   if (multipleSelection.value.length == 0) {
  //     return ElMessage.warning('请选择要删除的信息')
  //   }
  //   multipleSelection.value.forEach((item) => {
  //     ids.push(item.id)
  //   })
  // } else {
  ids = id
  // }
  // console.log(ids, multipleSelection.value, 'multipleSelection.value')

  try {
    const res = await api.removeAccount({ ids: ids.toString() })
    console.log(res, 'res')
    if (res.code == 200) {
      ElNotification({
        title: '成功',
        message: res.msg,
        type: 'success'
      })
      getAccounts()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.log(error)
    ElNotification({
      title: '失败',
      message: '删除失败',
      type: 'error'
    })
  }
}
// 修改角色配置
async function editRow(item: any) {
  tabRole.value = true
  addDialog.value = true
  form.username = item.username
  form.email = item.email
  form.phone = item.phone
  form.role_id = item.role_id
  state.id = item.id
}
// 取消操作
function treeClose(formEl: FormInstance | undefined) {
  addDialog.value = false
  tabRole.value = false
  if (!formEl) return
  formEl.resetFields()
}
// 添加账号/修改账号
async function addRole(formEl: FormInstance | undefined) {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res = null
      if (tabRole.value) {
        form.id = state.id
        res = await api.editAccount(form)
      } else {
        delete form.id
        res = await api.addAccount(form)
      }
      if (res.code == 200) {
        ElNotification({
          title: '成功',
          message: res.msg,
          type: 'success'
        })
        treeClose(ruleFormRef.value)
        getAccounts()
      } else {
        console.log(res.msg)
        ElNotification({
          title: '失败',
          message: res.msg,
          type: 'error'
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`)
  query.pageSize = val
  query.page = 1
  getAccounts()
}
const handleCurrentChange = (val: number) => {
  query.page = val
  getAccounts()
}
</script>

<style lang="less" scoped src="./css/account.less">

</style>
